package com.company.aicrawlers.controller.api;

import com.company.aicrawlers.common.dto.ApiResponse;
import com.company.aicrawlers.entity.CollectResult;
import com.company.aicrawlers.service.CollectResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采集数据上报 API Controller
 * 扩展调用此接口上报采集结果
 * 
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@RestController
@RequestMapping("/api/collect")
public class CollectDataApiController {

    @Autowired
    private CollectResultService collectResultService;

    /**
     * 上报单个采集结果
     * 扩展调用此接口
     * 
     * 接口：POST /api/collect/submit
     * 
     * @param requestBody 请求体
     * @return 成功信息
     */
    @PostMapping(value = "/submit", name = "submitResult")
    public ApiResponse<Map<String, Object>> submitResult(@RequestBody Map<String, Object> requestBody) {
        // 解析请求参数
        Long taskId = Long.valueOf(requestBody.get("taskId").toString());
        Long questionId = Long.valueOf(requestBody.get("questionId").toString());
        String questionContent = (String) requestBody.get("questionContent");
        String platform = (String) requestBody.get("platform");
        String answerContent = (String) requestBody.get("answerContent");
        String answerHtml = (String) requestBody.get("answerHtml");
        String collectTimeStr = (String) requestBody.get("collectTime");
        Integer responseTime = requestBody.get("responseTime") != null ? 
                (Integer) requestBody.get("responseTime") : null;
        String collectStatus = (String) requestBody.getOrDefault("collectStatus", "success");
        String errorMessage = (String) requestBody.get("errorMessage");

        // 创建结果对象
        CollectResult result = new CollectResult();
        result.setTaskId(taskId);
        result.setQuestionId(questionId);
        result.setQuestionContent(questionContent);
        result.setPlatformName(platform);
        result.setAnswerContent(answerContent);
        result.setAnswerHtml(answerHtml);
        result.setResponseTime(responseTime);
        result.setCollectStatus(collectStatus);
        result.setErrorMessage(errorMessage);

        // 解析采集时间
        if (collectTimeStr != null) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
                result.setCollectTime(LocalDateTime.parse(collectTimeStr, formatter));
            } catch (Exception e) {
                log.warn("解析采集时间失败: {}", collectTimeStr, e);
                result.setCollectTime(LocalDateTime.now());
            }
        } else {
            result.setCollectTime(LocalDateTime.now());
        }

        // 计算回答长度
        if (answerContent != null) {
            result.setAnswerLength(answerContent.length());
        }

        // 保存结果（会自动更新相关表的状态和统计）
        collectResultService.saveResult(result);

        // 返回成功信息
        Map<String, Object> response = new HashMap<>();
        response.put("resultId", result.getResultId());
        response.put("message", "上报成功");

        log.info("采集结果上报成功: taskId={}, questionId={}, platform={}, status={}", 
                taskId, questionId, platform, collectStatus);

        return ApiResponse.success(response, "上报成功");
    }

    /**
     * 批量上报采集结果
     * 
     * 接口：POST /api/collect/batch-submit
     * 
     * @param requestBody 请求体
     * @return 成功信息
     */
    @PostMapping(value = "/batch-submit", name = "batchSubmitResults")
    public ApiResponse<Map<String, Object>> batchSubmitResults(@RequestBody Map<String, Object> requestBody) {
        Long taskId = Long.valueOf(requestBody.get("taskId").toString());
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) requestBody.get("results");

        int successCount = 0;
        for (Map<String, Object> resultData : results) {
            resultData.put("taskId", taskId);
            try {
                submitResult(resultData);
                successCount++;
            } catch (Exception e) {
                log.error("批量上报失败: {}", resultData, e);
            }
        }

        Map<String, Object> response = new HashMap<>();
        response.put("totalCount", results.size());
        response.put("successCount", successCount);
        response.put("failCount", results.size() - successCount);

        return ApiResponse.success(response, "批量上报完成");
    }
}

